package datamodel;

import java.util.ArrayList;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamOmitField;

@XStreamAlias("Sign")
public class Field implements Observable {

	public static int EMPTY = -1;
	private int value;
	@XStreamOmitField
	private ArrayList<Integer> possibleValues;
	@XStreamOmitField
	private ArrayList<Observer> listener;

	public void init(int numberOfPossibleValues) {
		this.value = Field.EMPTY;
		if (possibleValues == null) {
			possibleValues = new ArrayList<Integer>();
		}
		if (possibleValues.size() == 0) {
			for (int i = 0; i < numberOfPossibleValues; i++) {
				possibleValues.add(i);
			}
		}
	}

	/**
	 * Compares the value of this Field with the value of f.
	 * 
	 * @param value
	 *            Value {@link Field#value} is compared to.
	 * @return <code>true</code> if both values are equal and not
	 *         {@link Field#EMPTY}
	 */
	public boolean isValueEqual(int value) {
		if (value != Field.EMPTY && this.getValue() != Field.EMPTY
				&& value == this.getValue()) {
			return true;
		} else {
			return false;
		}
	}

	public boolean isEmpty() {
		return value == Field.EMPTY;
	}

	public void setValue(int value) {
		this.value = value;
		notifyChange();
	}

	public int getValue() {
		return this.value;
	}

	public void setPossibleValues(ArrayList<Integer> possibleValues) {
		this.possibleValues = possibleValues;
		notifyChange();
	}

	public ArrayList<Integer> getPossibleValues() {
		return this.possibleValues;
	}

	@Override
	public String toString() {
		if (value == Field.EMPTY)
			return " ";
		return String.valueOf(value);
	}

	private void notifyChange() {
		if (listener != null) {
			for (Observer o : listener) {
				o.notifyChange();
			}
		}
	}

	@Override
	public void observe(Observer o) {
		if (listener == null) {
			listener = new ArrayList<Observer>();
		}
		listener.add(o);
	}

	@Override
	public void remove(Observer o) {
		int i = listener.indexOf(o);
		if (i >= 0) {
			listener.remove(i);
		}

	}
}
